<script setup lang="ts">
/**
 * @name Workbench
 * @description 工作台
 */
import Welcome from './components/Welcome.vue'
import TimeTypeFilter from './components/TimeTypeFilter.vue'
import EnergyOverview from './components/EnergyOverview.vue'
import EnergyTable from './components/EnergyTable.vue'
import EnergyPie from './components/EnergyPie.vue'
import EnergyChart from './components/EnergyChart.vue'

import { useWorkbench } from '@/mixins/MixinWorkbench'
import { STORAGE_MODES } from '@/enum/modules/indicator'

const timeType = ref(STORAGE_MODES.DAY)
const value = ref('')
const {
  cards,
  chartData,
  setChartData,
  getCards,
  getCharts,
} = useWorkbench()

const currentCard = computed(() => {
  return unref(cards).find(item => item.name === unref(value))
})
const indicatorNumber = computed(() => {
  const t = unref(currentCard)
  return t ? t.value : ''
})
const tableData = computed(() => {
  const t = unref(currentCard)
  // 只要有“指标”数据源参数才显示表格
  return t && t.value
    ? [
        { name: t.nowTime, value: t.now },
        { name: t.previousTime, value: t.previous },
        { name: t.beforePreviousTime, value: t.beforePrevious },
      ]
    : []
})
const pieData = computed(() => {
  const t = unref(currentCard)
  // 只有配置了“指标”的数据源参数才显示饼图
  return t && t.value
    ? [
        [t.nowTime, t.previousTime, t.beforePreviousTime],
        [t.now, t.previous, t.beforePrevious],
      ]
    : null
})

watch(
  () => unref(timeType),
  () => {
    getCards(timeType.value)
    if (unref(indicatorNumber)) {
      getCharts(timeType.value, indicatorNumber.value)
    }
    else {
      setChartData(null)
    }
  },
)
watch(
  () => unref(indicatorNumber),
  (val) => {
    if (val) {
      getCharts(timeType.value, val)
    }
    else {
      setChartData(null)
    }
  },
)

onMounted(async () => {
  await getCards(timeType.value)
  await nextTick()
  const head = unref(cards)[0]?.name || ''
  value.value = head
})
</script>

<template>
  <b-scrollbar
    class="padding-sm fill home flex flex-col gap-sm container"
  >
    <Welcome />
    <TimeTypeFilter v-model="timeType" style="background-color: transparent;" />
    <EnergyOverview v-model="value" style="margin-top: -21px;" :data="cards" :time-type="timeType" />
    <div class="flex gap-sm" style="height: 300px;">
      <div class="height-fill alpha-block width-1/2 overflow-hidden border rounded">
        <EnergyTable :data="tableData" :col-name="currentCard?.name || ''" />
      </div>
      <div class="width-1/2 height-fill alpha-block border rounded">
        <EnergyPie v-if="pieData" :data="pieData" :name="currentCard?.name || ''" />
        <TableEmpty v-else />
      </div>
    </div>
    <div class="alpha-block border" style="height: 400px;">
      <EnergyChart v-if="chartData" :data="chartData" :name="currentCard?.name || ''" />
      <TableEmpty v-else />
    </div>
  </b-scrollbar>
</template>

<style lang="scss" scoped>
.home {
  & > div {
    flex: 0 0 auto;
  }
}
</style>
